<template>
  <div class="message-page">
    <div class="message-header">
      <h2>我的消息</h2>
      <div class="message-tabs">
        <span :class="['tab', activeTab === 'all' ? 'active' : '']" @click="switchTab('all')">
          全部消息
        </span>

        <span :class="['tab', activeTab === 'unread' ? 'active' : '']" @click="switchTab('unread')">
          <el-badge :value="unreadCount" :hidden="unreadCount===0">
             未读消息
          </el-badge>
        </span>

        <span :class="['tab', activeTab === 'clue' ? 'active' : '']" @click="switchTab('clue')">
          <el-badge :value="clueCount" :hidden="clueCount===0">
             线索消息
          </el-badge>
        </span>

        <div style="display: flex;justify-content: flex-end">
          <el-button size="small" @click="markAllAsRead" class="mark-all-read">
            全部已读
          </el-button>
        </div>

      </div>

    </div>

    <div class="message-list">
      <div 
        v-for="message in filteredMessages" 
        :key="message.id"
        :class="['message-item', {'unread': message.isRead==='0'}]"
        @click="showMessageDetail(message)"
      >
        <div class="message-content">

          <div class="message-title">
            <el-tag
                v-if="message.type!=='comment'"
                :type="getTagType(message.type)"
                size="small"
                class="message-tag"
            >
              {{ getTagText(message.type) }}
            </el-tag>
            {{ message.title }}
            <span v-if="message.type==='clue'"> 向你提供了一条线索</span>
            <span v-if="message.isRead==='0'" class="unread-dot"></span>
          </div>


          <div class="message-text">
            <span v-if="message.type==='comment'">回复：</span>
            {{ message.content }}
          </div>

          <div class="message-time">{{ formatDateToDetail(message.createdDate) }}</div>
        </div>
        <el-button
          type="text"
          class="delete-btn"
          @click.stop="deleteMessage(message)"
        >
          <el-icon size="25"><Delete /></el-icon>
        </el-button>
      </div>
      <div v-if="filteredMessages.length === 0" class="empty-message">
        暂无消息
      </div>
    </div>

    <!-- 消息详情弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentMessage.title"
      width="50%"
      class="message-dialog"
    >
      <div class="message-detail">
        <div class="message-detail-header">
          <span class="message-detail-time">{{ formatDateToYYMMDDHHMMSS(currentMessage.createdDate) }}
          <span v-if="currentMessage.type==='comment'">回复了你</span>
          </span>

        </div>
        <div class="message-detail-content">
          <p>{{ currentMessage.content }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed,onMounted,watch } from 'vue'
import dayjs from 'dayjs'
import {queryMessageByUidAPI, updateMessageAPI,deleteMessageByMidAPI} from "@/apis/message";
import {useUserStore} from "@/stores/user";
import {formatDateToDetail,formatDateToYYMMDDHHMMSS} from "@/utils/formatDate";
import { Delete } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import {useRoute} from "vue-router";

const activeTab = ref('all')
const messages = ref([])
const route=useRoute()

async function getMyMessages() {
  await queryMessageByUidAPI(useUserStore().getUserInfo().uid).then(res=>{
    messages.value=res.data
  })
}

onMounted(()=>{
  getMyMessages()
  activeTab.value=route.query.type===undefined?'all':route.query.type
})

watch(route,(newVal,oldVal)=>{
  activeTab.value=newVal.query.type===undefined?'all':newVal.query.type
})

const filteredMessages = computed(() => {
  if (activeTab.value === 'unread') {
    return messages.value.filter(msg => msg.isRead==='0')
  }else if(activeTab.value === 'clue'){
    return messages.value.filter(msg => msg.type==='clue')
  }
  return messages.value
})

const unreadCount = computed(() => {
  return messages.value.filter(msg => msg.isRead==='0').length
})

const clueCount= computed(() => {
  return messages.value.filter(msg => msg.type==='clue'&&msg.isRead==='0').length
})

const dialogVisible = ref(false)
const currentMessage = ref({})

const switchTab = (tab) => {
  activeTab.value = tab
}

const readMessage = async (message) => {
  message.isRead = 1
  //调用API更新消息状态
  await updateMessageAPI(message)
}

const showMessageDetail = (message) => {
  currentMessage.value = message
  dialogVisible.value = true
  readMessage(message)
}

const getTagType = (type) => {
  switch (type) {
    case 'system':
      return 'danger'
    case 'police':
      return 'info'
    case 'clue':
      return 'success'
    default:
      return ''
  }
}

const getTagText = (type) => {
  switch (type) {
    case 'system':
      return '系统通知'
    case 'police':
      return '警方通知'
    case 'clue':
      return '线索消息'
    default:
      return ''
  }
}

// 添加删除消息方法
const deleteMessage = async (message) => {
  try {
    await ElMessageBox.confirm('确定要删除这条消息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // TODO 删除消息
    await deleteMessageByMidAPI(message.mid).then(res=>{
      if(res.code==='200'){
        ElMessage.success('删除成功')
        messages.value = messages.value.filter(item => item.mid !== message.mid)
      }
    })
  } catch (error) {
    // 用户取消删除
  }
}

// 添加全部已读方法
const markAllAsRead = async () => {
  const unreadMessages = messages.value.filter(msg => msg.isRead === '0')
  if (unreadMessages.length === 0) {
    ElMessage.warning('没有未读消息')
    return
  }
  try {
    // 更新所有未读消息
    await Promise.all(unreadMessages.map(msg => readMessage(msg)))
    ElMessage.success('已将所有消息标记为已读')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}
</script>

<style scoped>
.message-page {
  padding: 20px;
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
}

.message-header {
  margin-bottom: 20px;
  flex-shrink: 0;
}

.message-tabs {
  margin-top: 15px;
}

.tab {
  position: relative;
  padding: 8px 16px;
  margin-right: 15px;
  cursor: pointer;
}

.tab.active {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
}

.message-item {
  padding: 15px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-item:hover {
  background-color: #f5f7fa;
}

.message-item.unread {
  background-color: #f0f9ff;
}

.message-title {
  font-weight: bold;
  margin-bottom: 8px;
}

.message-text {
  color: #666;
  margin-bottom: 8px;
}

.message-time {
  font-size: 12px;
  color: #999;
}

.empty-message {
  text-align: center;
  padding: 30px;
  color: #999;
}

.unread-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #f56c6c;
  margin-left: 6px;
}

.message-detail {
  padding: 20px;
}

.message-detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.message-detail-time {
  color: #999;
  font-size: 13px;
}

.message-detail-content {
  line-height: 1.6;
  color: #333;
  font-size: 14px;
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 4px;
}

.delete-btn {
  display: none;
  color: #f56c6c;
}

.message-item:hover .delete-btn {
  display: block;
}

.mark-all-read {

}

/* 添加新的弹窗样式 */
.message-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #eee;
  padding: 15px 20px;
  margin-right: 0;
}

.message-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.message-detail {
  padding: 20px;
}

.message-detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.message-detail-time {
  color: #999;
  font-size: 13px;
}

.message-detail-content {
  line-height: 1.6;
  color: #333;
  font-size: 14px;
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 4px;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  min-height: 200px;
}
</style>
